<template>
  <div class="callback-container">
    <div v-if="loading" class="loading-wrapper">
      <div class="loading-spinner"></div>
      <p>正在登录中...</p>
    </div>
    <div v-if="error" class="error-message">
      <p>{{ error }}</p>
      <router-link to="/login">返回登录</router-link>
    </div>
  </div>
</template>

<script setup>
import { useUserStore } from '@stores/userStore'

const router = useRouter()
const route = useRoute()
const store = useUserStore()
const loading = ref(true)
const error = ref(null)

const handleLogin = async (provider, code) => {
  try {
    const response = await axios.get(`/api/auth/callback/${provider}/`, { params: { code } })
    const data = response.data
    if (data.user) {
      store.setAuthInfo(data.access, data.user.username)
      router.push('/') // 导航到主页或其他指定页面
    }
  } catch (err) {
    console.error('授权失败:', err)
    error.value = '登录失败：' + (err.response?.data?.message || '未知错误')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  const provider = route.path.split('/').filter(Boolean).pop() // 获取路径中的最后一个部分作为provider
  const code = route.query.code // 从查询参数中获取code
  if (provider && code) {
    handleLogin(provider, code)
  } else {
    error.value = '无效的回调URL'
    loading.value = false
  }
})
</script>



<style scoped>
.callback-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f5f5f5;
}

.loading-wrapper {
  text-align: center;
}

.loading-spinner {
  display: inline-block;
  width: 40px;
  height: 40px;
  border: 3px solid rgba(0, 0, 0, 0.1);
  border-radius: 50%;
  border-top-color: #1890ff;
  animation: spin 1s linear infinite;
  margin-bottom: 16px;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.error-message {
  text-align: center;
  color: #ff4d4f;
  padding: 24px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.error-message a {
  color: #1890ff;
  text-decoration: none;
  margin-top: 12px;
  display: block;
}
</style>
